package com.sunny.fetch.common;

import com.sunny.common.utils.IDUtil;
import com.sunny.common.utils.StringUtil;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: sublun
 * @Date: 2021/3/25 20:05
 */
public class ResultData extends HashMap {
    public String getRequestId() {
        return (String) get("request_id");
    }
    public int getCode() {
        Object code = get("code");
        return Integer.parseInt(code.toString());
    }
    public String getMsg() {
        return (String) get("msg");
    }
    public ArrayList<String> getFields() {
        return (ArrayList<String>)((Map) get("data")).get("fields");
    }

    @SuppressWarnings("rawtypes")
    public List<Map> getItems() {
        ArrayList<String> fields = (ArrayList<String>)((Map) get("data")).get("fields");
        ArrayList items = (ArrayList) ((Map) get("data")).get("items");
        List<Map> mapList = (List<Map>) items.stream().map(e->{
            ArrayList item = (ArrayList) e;
            Map m = new HashMap();
            for (int i = 0; i < item.size(); i++) {
                m.put(fields.get(i), item.get(i));
            }
            return m;
        }).collect(Collectors.toList());
        return mapList;
    }

    public <T> List<T> getItems(Class<T> tClass) {
        List<Map> items = getItems();
        List<T> list = items.stream().map(map -> {
            T t = null;
            try {
                t = tClass.newInstance();
                Field tidField = t.getClass().getDeclaredField("tid");
                //设置私有变量可以修改
                tidField.setAccessible(true);
                tidField.set(t, IDUtil.genId());
                for (Object key : map.keySet()) {
                    try {
                        Field field = t.getClass().getDeclaredField(StringUtil.lineToHump((String) key));
                        //设置私有变量可以修改
                        field.setAccessible(true);
                        field.set(t, map.get(key));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            return t;
        }).collect(Collectors.toList());

        return list;
    }

    public Boolean hashMore() {
        return (Boolean) ((Map) get("data")).get("has_more");
    }

}
